package com.hpf.cloud.controller;

import cn.hutool.core.util.IdUtil;
import com.hpf.cloud.constants.CommonConstants;
import com.hpf.cloud.entity.ErrorCode;
import com.hpf.cloud.pojo.CommonResult;
import com.hpf.cloud.service.es.ErrorCodeRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * @description: 错误码控制层
 * @datetime: 2020/12/4 22:36
 * @author: huangpengfei
 */
@RestController
@ResponseBody
@Slf4j
public class ErrorController {

    @Autowired
    private ErrorCodeRepository errorCodeRepository;

    /**
     * 根据errorCode 查询错误码信息
     *
     * @param errorCode
     * @return
     */
    @GetMapping("/findErrorCodeByCode")
    public CommonResult findErrorCodeByCode(@RequestParam("errorCode") String errorCode) {
        return CommonResult.ok(errorCodeRepository.findByErrorCode(errorCode));
    }

    /**
     * 插入errorCode
     *
     * @param errorCode
     * @return
     */
    @PostMapping("/save")
    public CommonResult save(@RequestBody ErrorCode errorCode) {
        // 统一设置errorCode的id为雪花算法
        errorCode.setId(IdUtil.getSnowflake(1, 1).nextId());
        // 默认fred,todo 获取当前用户
        errorCode.setCreateUser("fred");
        errorCode.setCreateTime(LocalDateTime.now());
        errorCode.setPhysicalFlag(CommonConstants.PhysicalFlag.PHYSICAL_FLAG_DELETE_FALSE);
        errorCodeRepository.save(errorCode);
        return CommonResult.ok();
    }

    /**
     * 根据errorCode 查询错误码信息
     *
     * @param errorCode
     * @return
     */
    @DeleteMapping("/deleteErrorCode/{errorCode}")
    public CommonResult deleteErrorCode(@PathVariable("errorCode") String errorCode) {
        errorCodeRepository.deleteByErrorCode(errorCode);
        return CommonResult.ok();
    }
}
